package com.cg.offer;

import com.cg.leetcode.ListNode;
import org.junit.Test;

/**
 * 剑指Offer 25.合并两个排序的链表
 *
 * @program: LeetCode->Offer_25
 * @description: 剑指Offer 25.合并两个排序的链表
 * @author: cg
 * @create: 2022-03-20 14:40
 **/
public class Offer_25 {

    @Test
    public void test25() {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);
        System.out.println(mergeTwoLists(l1, l2));
        System.out.println(mergeTwoLists(null, null));
    }

    /**
     * 输入两个递增排序的链表，合并这两个链表并使新链表中的节点仍然是递增排序的。
     * <p>
     * 示例1：
     * 输入：1->2->4, 1->3->4
     * 输出：1->1->2->3->4->4
     * <p>
     * 限制：
     * 0 <= 链表长度 <= 1000
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode perRes = new ListNode(-1);
        ListNode current = perRes;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                current.next = l1;
                l1 = l1.next;
            } else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }
        if (l1 != null) {
            current.next = l1;
        } else {
            current.next = l2;
        }
        return perRes.next;
    }

}
